package com.firewolf.rbac.service.impl;

import com.firewolf.rbac.mapper.MenuMapper;
import com.firewolf.rbac.pojo.Menu;
import com.firewolf.rbac.pojo.MenuExample;
import com.firewolf.rbac.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/3/3
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findAll() {
        return findMenusById(0L, "顶级菜单");
    }

    private List<Menu> findMenusById(Long parent_id, String parentname) {
        MenuExample me = new MenuExample();
        MenuExample.Criteria criteria = me.createCriteria();
        criteria.andParentIdEqualTo(parent_id);
        me.setOrderByClause("order_num asc");
        List<Menu> menus = menuMapper.selectByExample(me);
        for (Menu m : menus) {
            m.setCreateTime(null);
            m.setLastUpdateTime(null);
            m.setParentname(parentname);
            List<Menu> childrens = findMenusById(m.getId(), m.getName());
            m.setChildren(childrens);
        }
        return menus;
    }

    @Override
    public void save(Menu menu) {
        if(menu.getId() == null){
            menu.setCreateTime(new Date());
            menu.setLastUpdateTime(new Date());
            menu.setDelFlag((byte)0);
            menuMapper.insert(menu);
        }else{
            menu.setLastUpdateTime(new Date());
            menuMapper.updateByPrimaryKeySelective(menu);
        }
    }
}
